﻿using ERPWinFormWork.Product.ProductErrorCode;
using ERPWinFormWork.Sales.DTO;
using ERPWinFormWork.Sales.DTO.Output;
using ERPWinFormWork.Sales.ErrorCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Sales
{
    public partial class QuotationAddForm : Form
    {
        private Form1 form1;
        private ApiClient _apiClient;
        private Dictionary<int, ProductPriceCacheModel> _productPriceCache;

        // 新增：产品价格缓存模型（存储原始价格和税率）
        private class ProductPriceCacheModel
        {
            public decimal UntaxedPrice { get; set; } // 原始未税价格
            public decimal TaxRate { get; set; }      // 原始税率
        }
        public QuotationAddForm()
        {
            InitializeComponent();
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            GetCustomerSelect();
            ColumnsAdd(); // 初始化列（在绑定数据前执行）
            form1= new Form1();
            _productPriceCache = new Dictionary<int, ProductPriceCacheModel>();
        }

        /// <summary>
        /// 客户下拉
        /// </summary>
        private async void GetCustomerSelect()
        {
            var response = await _apiClient.GetAsync<ApiResponse<List<Customer>>>(
                    endpoint: "Sales/CustomerGet"
                );
            if (response != null && response.code == 200)
            {
                var customerList = new List<Customer>
                {
                    new Customer { id = 0, Customer_Name = "请选择" }
                };
                customerList.AddRange(response.data);
                cboCustomer.DataSource = customerList;
                cboCustomer.DisplayMember = "Customer_Name";
                cboCustomer.ValueMember = "id";
                cboCustomer.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 添加按钮 获取产品数据
        /// </summary>
        private void btnStepwiseAdd_Click(object sender, EventArgs e)
        {
            using (ProductAddForm productForm = new ProductAddForm())
            {
                if (productForm.ShowDialog() == DialogResult.OK)
                {


                    // 使用BindingList确保数据变更能实时反映到界面
                    var bindingList = new BindingList<ProductModel>(productForm.SelectedProducts);
                    dgvproduct.DataSource = bindingList;


                    // 给操作列设置"移除"文本
                    foreach (DataGridViewRow row in dgvproduct.Rows)
                    {
                        if (row.DataBoundItem == null) continue; // 跳过空行
                        row.Cells["ColOperation"].Value = "移除";

                       
                    }
                }
            }
        }

        /// <summary>
        /// 初始化表格列（核心修改：添加DataPropertyName关联属性）
        /// </summary>
        private void ColumnsAdd()
        {
            // 使用通用方法添加列，确保列与ProductModel属性关联
            AddTextColumn("Product_Name", "产品名称", "Product_Name");
            AddTextColumn("Product_Number", "产品编号", "Product_Number");
            AddTextColumn("Specification", "规格型号", "Specification");
            AddTextColumn("Finished_Type", "产品类型", "Finished_Type");
            AddTextColumn("Unit", "单位", "Unit");
            AddTextColumn("Tax_Rate", "税率", "Tax_Rate", format: "P2"); // 百分比格式
            AddTextColumn("Untaxed_Price", "原未税价格", "Untaxed_Price", format: "N2"); // 保留2位小数
            AddTextColumn("Price_Including", "原含税价格", "Price_Including", format: "N2");
            AddTextColumn("Sales_Quantity", "数量", "Sales_Quantity", format: "N2");
            AddTextColumn("New_Price", "新未税价格", "New_Price", format: "N2");
            AddTextColumn("Price_Tex", "新含税价格", "Price_Tex", format: "N2");
            AddTextColumn("Particulars_Descr", "备注", "Particulars_Descr", width: 150);
            AddTextColumn("ColOperation", "操作", null, isReadOnly: true, width: 80); // 操作列无绑定属性

         

            // 注册事件（数量编辑完成后计算折扣）
            dgvproduct.CellEndEdit += dgvproduct_CellEndEdit;
            dgvproduct.CellClick += dgvproduct_CellClick;

            // 设置DataGridView基础属性
            dgvproduct.AutoGenerateColumns = false; // 禁止自动生成列
            dgvproduct.AllowUserToAddRows = false;  // 禁止用户新增行
            dgvproduct.ReadOnly = false;            // 整体可编辑（数量列）
            dgvproduct.SelectionMode = DataGridViewSelectionMode.FullRowSelect; // 整行选择
        }

        /// <summary>
        /// 通用列创建方法（封装重复逻辑，设置DataPropertyName）
        /// </summary>
        private void AddTextColumn(
            string columnName,
            string headerText,
            string dataPropertyName,
            bool isReadOnly = false,
            int width = -1,
            string format = ""
        )
        {
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
            column.Name = columnName;
            column.HeaderText = headerText;
            column.ReadOnly = isReadOnly;

            // 关键：关联ProductModel的属性
            if (!string.IsNullOrEmpty(dataPropertyName))
            {
                column.DataPropertyName = dataPropertyName;
            }

            // 设置列宽
            if (width > 0)
            {
                column.Width = width;
            }
            else
            {
                column.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }

            // 设置数据格式（如价格、百分比）
            if (!string.IsNullOrEmpty(format))
            {
                column.DefaultCellStyle.Format = format;
            }

            dgvproduct.Columns.Add(column);
        }

        /// <summary>
        /// 移除行功能
        /// </summary>
        private void dgvproduct_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 修复1：优先过滤无效行索引（必须放在最前面）
            if (e.RowIndex < 0)
                return; // 点击列标题或空白区域，直接返回

            // 修复2：过滤已删除/无效的行（避免索引超出集合大小）
            if (e.RowIndex >= dgvproduct.Rows.Count)
                return;

            // 修复3：先获取当前行，判断是否有效（避免行已被移除）
            DataGridViewRow currentRow = dgvproduct.Rows[e.RowIndex];
            if (currentRow == null || currentRow.IsNewRow || currentRow.DataBoundItem == null)
                return;

            // 修复4：判断列索引（先检查列是否存在，避免列名错误导致的索引异常）
            DataGridViewColumn operationColumn = dgvproduct.Columns["ColOperation"];
            if (operationColumn == null || e.ColumnIndex != operationColumn.Index)
                return;

            // 修复5：判断"移除"文本（避免空值导致的ToString()异常）
            string cellValue = currentRow.Cells["ColOperation"].Value?.ToString() ?? "";
            if (cellValue != "移除")
                return;

            // 至此，所有条件均有效，执行移除逻辑
            if (dgvproduct.DataSource is BindingList<ProductModel> bindingList)
            {
                // 修复6：强转前判断数据类型，避免转换失败
                if (currentRow.DataBoundItem is ProductModel product)
                {
                    bindingList.Remove(product);
                    // 可选：移除缓存中对应的产品（保持缓存与数据源同步）
                    if (_productPriceCache.ContainsKey(product.Id))
                    {
                        _productPriceCache.Remove(product.Id);
                    }
                }
                else
                {
                    MessageBox.Show("当前行数据异常，无法移除产品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            // 兼容非BindingList数据源（兜底逻辑）
            else if (dgvproduct.Rows.Count > e.RowIndex)
            {
                dgvproduct.Rows.RemoveAt(e.RowIndex);
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            // 1. 初始化核心对象，提前确保集合非空（避免Add时空引用）
            QuotationAdd add = new QuotationAdd();
            add.quotationParticularsDTOs = new List<QuotationParticularsCommandDTO>(); // 关键：初始化集合

            try
            {
                if (cboCustomer.SelectedValue == null
                    || !int.TryParse(cboCustomer.SelectedValue.ToString(), out int customerId)
                    || customerId <= 0)
                {
                    MessageBox.Show("请选择有效的客户（非“请选择”选项）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 报价名称/编号非空校验
                string quotationName = txtQuotationName.Text.Trim();
                string quotationNumber = txtQuotationNumber.Text.Trim();
                if (string.IsNullOrEmpty(quotationName))
                {
                    MessageBox.Show("报价名称不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (string.IsNullOrEmpty(quotationNumber))
                {
                    MessageBox.Show("报价编号不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 税率校验：避免非数字/负数
                if (!decimal.TryParse(txtQuotationTax_Rate.Text.Trim(), out decimal taxRate) || taxRate < 0)
                {
                    MessageBox.Show("税率格式错误（需输入非负数字）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 封装主报价信息（校验通过后再赋值）
                QuotationCommandDTO quotation = new QuotationCommandDTO()
                {
                    Customer_Id = customerId,
                    Quotation_Descr = txtQuotationDescr.Text.Trim(),
                    Quotation_Name = quotationName,
                    Quotation_Number = quotationNumber,
                    Tax_Rate = taxRate  
                };
                add.quotationDTO = quotation;

                // 3. 产品明细遍历 + 优化校验
                foreach (DataGridViewRow row in dgvproduct.Rows)
                {
                    // 跳过空行和新增行（保留原有逻辑，补充Trim处理）
                    if (row.DataBoundItem == null || row.IsNewRow)
                        continue;

                    // 产品模型强转优化：避免强制转换失败（增加类型判断）
                    if (!(row.DataBoundItem is ProductModel product))
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行数据异常，无法识别产品信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    // 产品ID校验：避免无效ID（如负数/0）
                    if (product.Id <= 0)
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行产品ID无效（需为正整数）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    int productId = product.Id;

                    // 新未税价格：补充Trim（避免用户输入空格）+ 非负校验
                    string newPriceStr = row.Cells["New_Price"].Value?.ToString()?.Trim();
                    if (!decimal.TryParse(newPriceStr, out decimal newPrice) || newPrice < 0)
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行新未税价格格式错误（需输入非负数字）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    // 新含税价格：同未税价格优化
                    string priceTexStr = row.Cells["Price_Tex"].Value?.ToString()?.Trim();
                    if (!decimal.TryParse(priceTexStr, out decimal priceTex) || priceTex < 0)
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行新含税价格格式错误（需输入非负数字）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    //数量
                    string salesQuantityStr = row.Cells["Sales_Quantity"].Value?.ToString()?.Trim();
                    if (string.IsNullOrEmpty(salesQuantityStr))
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行数量不能为空", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (!int.TryParse(salesQuantityStr, out int salesQuantity) || salesQuantity <= 0)
                    {
                        MessageBox.Show($"第 {row.Index + 1} 行数量格式错误（需输入大于0的数字）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    // 备注：优化空值处理（统一转为空字符串，避免后续null问题）
                    string particularsDescr = row.Cells["Particulars_Descr"].Value?.ToString()?.Trim() ?? string.Empty;

                    // 封装明细（保留原有逻辑）
                    QuotationParticularsCommandDTO item = new QuotationParticularsCommandDTO()
                    {
                        Product_Id = productId,
                        New_Price = newPrice,
                        Price_Tex = priceTex,
                        Particulars_Descr = particularsDescr,
                        Sales_Quantity= salesQuantity
                    };
                    add.quotationParticularsDTOs.Add(item);
                }

                // 4. 最终校验：确保有产品明细
                if (add.quotationParticularsDTOs.Count == 0)
                {
                    MessageBox.Show("请至少添加一条产品明细后再提交", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                Add(add);



            }
            catch (Exception ex)
            {
                // 统一捕获意外错误（如单元格不存在、值异常等），避免程序崩溃
                MessageBox.Show($"操作失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 发送POST请求
        /// </summary>
        private async void Add(QuotationAdd discountData)
        {
            var response = await _apiClient.PostAsync<QuotationAdd, ApiResponse<string>>(
                endpoint: "Sales/QuotationAdd",
                data: discountData
            );

            if (response != null && response.code == 200)
            {

                MessageBox.Show("销售报价添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                form1.GetDataQuotation();
                this.Close();
            }
            else
            {
                MessageBox.Show($"提交失败：{response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void dgvproduct_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // 检查是否编辑的是数量列
            if (e.RowIndex < 0 || dgvproduct.Columns[e.ColumnIndex].Name != "Sales_Quantity")
                return;

            var row = dgvproduct.Rows[e.RowIndex];
            if (row.DataBoundItem is ProductModel product)
            {
                // 验证数量是否有效
                if (!decimal.TryParse(row.Cells["Sales_Quantity"].Value?.ToString(), out decimal quantity) || quantity <= 0)
                {
                    MessageBox.Show("请输入有效的数量（大于0的数字）", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 验证是否已选择客户
                if (cboCustomer.SelectedValue == null || !int.TryParse(cboCustomer.SelectedValue.ToString(), out int customerId) || customerId <= 0)
                {
                    MessageBox.Show("请先选择客户再计算折扣", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                try
                {

                    var parameters = new Dictionary<string, string>
                {
                    { "ProctorId", product.Id.ToString() },
                    { "CustomerId", customerId.ToString() },
                    { "Price",product.Untaxed_Price.ToString("F2") }, // 保留2位小数
                    { "Number", quantity.ToString("F0") } // 数量按整数传递（根据接口要求调整）
                };

                    var response = await _apiClient.GetAsync<ApiResponse<decimal>>(
               endpoint: "Sales/Discountcomputer",
               parameters: parameters
           );
                    if (response != null && response.code == 200 && response.data >= 0)
                    {
                        var taxRate = product.Tax_Rate;
                        var newTaxedPrice = response.data * (1 + taxRate); // 计算新含税价格

                        // 更新界面显示
                        row.Cells["New_Price"].Value = response.data;
                        row.Cells["Price_Tex"].Value = newTaxedPrice;

                        // 更新数据源（保证数据同步）
                        product.New_Price = response.data;
                        product.Price_Tex = newTaxedPrice;
                    }
                    else
                    {

                        

                        // 更新界面和数据源
                        row.Cells["New_Price"].Value = product.Untaxed_Price;
                        row.Cells["Price_Tex"].Value = product.Price_Including;
                        product.New_Price = product.Untaxed_Price;
                        product.Price_Tex = product.Price_Including;
                      
                    }
                }
                catch (Exception ex)
                {
                    // 异常处理
                   
                    MessageBox.Show($"计算折扣时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

        }


       
    }
}
